<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>
    <div class="container">
    <table class="table">
        <caption>文章表</caption>
        <thead>
         <tr>
             <td>序号</td>
             <td>标题</td>
             <td>作责</td>
         </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    </div>
    <!-- 布局的类名 -->
    <a href="http://www.baidu.com" id="link">百度</a>
    <div class="row">
      <div class="col-md-8">1</div>
      <div class="col-md-4">2</div>
    </div>
    <form name="postform">
        <div class="form-group">
            <label for="authorInput">标题</label>
            <input type="text"name="title" class="form-control" id="authorInput"
            placeholder="请输入标题" required>
        </div>
        <div class="form-group">
            <label for="titleInput">作者</label>
            <input type="text" name="author" class="form-control" id="titleInput"
            placeholder="请输入作者" required>
        </div>
        <button type="submit" class="btn btn-default">添加</button>
    </form>
    <script>
        const oform=document.forms['postform'];
        const oTBody=document.querySelector('table tbody');
        console.log(oform);
        const link=document.getElementById('link');
        let id=3;
        // 功能抽象  post对象  变成tr html 字符串
        const getPostHtml=(post)=>`
        <tr>
                <td>${post.id}</td>
                <td>${post.title}</td>
                <td>${post.author}</td>
                <tr>
        `
        link.addEventListener('click',function(event){
            event.preventDefault();
        }
            );
        
        oform.addEventListener('submit',function(event){
// form 默认会向后端提交
//console.log('请不要向后端提交数据')
event.preventDefault();
            const title=oform["title"].value.trim();
            console.log(title);
            const author=oform["author"].value.trim();
            oTBody
            .innerHTML+=getPostHtml({
                id,
                title,
                author
            });
                    id++;
                    oform.reset();
        }
            );

        fetch('http://localhost:3000/posts')
        .then(data=>data.json())
        .then(data=>{
            // 前端和后端通信的数据格式是 json
            //console.log(data)
            oTBody.innerHTML=
            data.map(post=>
            getPostHtml(post)).join('');
            console.log('aaaaaaaaaaaaaaaa');
        })
        console.log('11111111');
    </script>
</body>
</html>